<?php
/*
	(c) 2006, 2007 Jan Lehnardt <jan@php.net>

	All rights reserved.
	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:
	* Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
	* Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
	* Neither the name of Couch PHP Library nor the names of its contributors may 
	be used to endorse or promote products derived from this software 
	without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
	EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
	DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	*/

	// dev help
	// error_reporting(E_ALL);
	// ini_set('display_errors', 'On');

	//PHP 5+ only!

	
$_couch_lib_path = dirname(__FILE__)."/../";
//ini_set("include_path", "$_couch_lib_path:$include_path");
require_once "HTTP/Request.php";

class _CouchCollection extends _CouchTransport
{	
	protected $_collection = array();

	public function __construct($arguments)
	{
		foreach($arguments AS $attribute => $value) {
			$this->$attribute = $value;
		}
	}

	public function _get($key, $class, $master)
	{
		if(!isset($this->_collection[$key])) {
			$this->_collection[$key] = new $class($key, $master);
		}

		return $this->_collection[$key];
	}   
}

class Couch extends _CouchCollection
{
	protected $host = '';
	protected $port = -1;

	public function __construct($arguments)
	{
		parent::__construct($arguments);
	}

	public function database($database_name)
	{
		return $this->_get($database_name, "CouchDatabase", $this);
	}
	
	/**
	 * Determines if CouchDb is running
	 *
	 * @return bool
	 **/
	function running()
	{
		$socket = @fsockopen($this->host, $this->port, $errno = -1, $errstr = '', $timeout = 10);
		if(!$socket) {
			//$this->throw_error("Cannot connect to CouchDb on {$this->host}:{$this->port}", E_USER_NOTICE);
			return false;
		}
		return true;
	}
	
	public function host()
	{
		return $this->host;
	}

	public function port()
	{
		return $this->port;
	}
}

class CouchDatabase extends _CouchCollection
{
	protected $name = '';
	protected $_couch;
	
	public function __construct($database_name, $couch)
	{
		$this->_couch = $couch;
		parent::__construct(array("name" => $database_name));
	}
	
	public function view($database_name)
	{
		return $this->_get($database_name, "CouchView", $this);
	}
	
	public function get($id)
	{
		$host = $this->_couch->host();
		$port = $this->_couch->port();
		
		// Try to get the document from CouchDb
		$_doc = $this->sendRequest("http://{$host}:{$port}/{$this->name}/{$id}", "GET");
		
		// Initialize empty document with the given ID
		$doc = new CouchDocument($id, NULL, $this);
		
		if ($_doc)
		{
            // If we got data from database we can populate the object with it
    		$doc->initFromStdClass($_doc);
        }
        
		return $doc;
	}
	
	public function name()
	{
		return $this->name;
	}
	
	public function couch()
	{
		return $this->_couch;
	}
	
	public function newView()
	{
		return new CouchView("", $this);
	}
	
	public function newDocument($id = NULL, $rev = NULL)
	{
		return new CouchDocument($id, $rev, $this);
	}
	
	public function exists()
	{
		$host = $this->_couch->host();
		$port = $this->_couch->port();
		$this->sendRequest("http://{$host}:{$port}/{$this->name}/", "GET");
		// var_dump($this->lastStatusCode);
		return ($this->lastStatusCode == 200);
	}
	
	public function create()
	{
		var_dump("in create");
		$host = $this->_couch->host();
		$port = $this->_couch->port();
		$this->sendRequest("http://{$host}:{$port}/{$this->name}", "PUT");
		return ($this->lastStatusCode == '200');
	}
}

class CouchView extends _CouchCollection
{
	protected $name = '';
	protected $_database;
	public $function;
	
	public function __construct($view_name, $database)
	{
		$this->_database = $database;
		parent::__construct(array("name" => $view_name));
	}
	
	public function documents()
	{
		$this->_fetch();
		return $this->_collection;
	}
	
	private function _fetch()
	{
		
		$db = $this->_database->name();
		$couch = $this->_database->couch();
		$host = $couch->host();
		$port = $couch->port();

		$headers = array("Content-Type" => "text/javascript");
		if(strlen($this->name) == 0) { //new view
			$view = '_temp_view';
			$this->_collection = $this->sendRequest("http://{$host}:{$port}/$db/$view", "POST", $this->function, $headers)->rows;
		} else {
			$view = $this->name;
			$this->_collection = $this->sendRequest("http://{$host}:{$port}/$db/$view", "GET", $post_data = false, $headers)->rows;
		}

		if(!is_array($this->_collection)) {
			$this->_collection = array();
		}
		
		foreach($this->_collection AS $idx => $document) {
			$obj = new CouchDocument(NULL, NULL, $this->_database);
			$obj->initFromStdClass($document);
			unset($this->_collection[$idx]);
			$this->_collection[$idx] = $obj;
		}
	}
	
	private function _castToCouchDocument($elm)
	{
		$obj = new CouchDocument($this->_database);
		$obj->initFromStdClass($elm);
		unset($elm);
		return $obj;
	}
}
// 
// class CouchDocument extends _CouchCollection
// {
// 	protected $name = '';
// 	protected $_database;
// 	public function __construct($view_name, $database)
// 	{
// 		$this->_database = $database;
// 		parent::__construct(array("name" => $view_name));
// 	}
// 	
// 	public function revisions()
// 	{
// 		return $this->_collection;
// 	}
// }

class CouchDocument extends _CouchTransport
{
	protected $_database;
	protected $_id;
	protected $_rev;
	
	public function __construct($id, $rev, $database)
	{
		$this->_id = $id;
		$this->_rev = (string)$rev;
		$this->_database = $database;
	}
	
	public function id()
	{
		return $this->_id;
	}

	public function rev()
	{
		if($this->_rev) {
			return (string)$this->_rev;
		}
	}
	
	public function save()
	{
		$db = $this->_database->name();
		$couch = $this->_database->couch();
		$host = $couch->host();
		$port = $couch->port();
		// debug_print_backtrace();
		if($this->_id) {
			$result = $this->sendRequest("http://{$host}:{$port}/$db/{$this->_id}", "PUT", $this->toString(), array("_rev" => $this->rev()));
		} else {
			$result = $this->sendRequest("http://{$host}:{$port}/$db/{$this->_id}", "POST", $this->toString(), array("_rev" => $this->rev()));
		}
		return ($this->lastStatusCode >199 && $this->lastStatusCode < 300);
	}
	
	public function delete()
	{
		$db = $this->_database->name();
		$couch = $this->_database->couch();
		$host = $couch->host();
		$port = $couch->port();
		$result = $this->sendRequest("http://{$host}:{$port}/$db/{$this->_id}", "DELETE");
		return ($this->lastStatusCode >199 && $this->lastStatusCode < 300);

	}
	
	public function initFromStdClass($obj)
	{
		foreach(get_object_vars($obj) AS $attribute => $value) {
			$this->$attribute = $value;
		}
		
		$db = $this->_database->name();
		$couch = $this->_database->couch();
		$host = $couch->host();
		$port = $couch->port();
		$result = $this->sendRequest("http://{$host}:{$port}/$db/{$this->_id}", "GET");
		foreach(get_object_vars($result) AS $attribute => $value) {
			// if("_rev" == $attribute) {
			// 	$this->$attribute = (string);
			// } else {
			// 	$this->$attribute = $value;
			// }
		 	$this->$attribute = $value;
		}
		
		// var_dump($this);
//		return ($this->lastStatusCode >199 && $this->lastStatusCode < 300);
	}
	
	public function toString()
	{
		$obj = new stdClass;
		foreach(get_object_vars($this) AS $attribute => $value) {
			if($attribute[0] == "_") { continue;}
			$obj->$attribute = $value;
		}
		
		if($this->_id) {
			$obj->_id = $this->_id;
		}

		if($this->_rev) {
			$obj->_rev = (int)$this->_rev;
		}
		
		$s = json_encode($obj);
		// var_dump($s);
		return $s;
	}
	
	public function get($name)
	{
		return $this->$name;
	}
	
	public function set($name, $value)
	{
		$this->$name = $value;
	}
}

class _CouchTransport
{
	function sendRequest($url, $method, $post_data = false, $headers = false)
	{
		if(empty($method)) {
			return false;
		}
		
	//	$options = $this->request_options;
		$options['method'] = $method;
		// $options['user'] = $this->user;
		// $options['pass'] = $this->pass;
		// $options['http'] = "1.0";
		$options['allowRedirects'] = true;
		$options['timeout'] = 3;
		
		// $host = $this->_database->_couch->host;
		// $port = $this->_database->_couch->port;
		// 
		// $url = "http://{$host}:{$port}/$url";
		$req = new HTTP_Request($url, $options);
		if($post_data) {
			$req->addRawPostData($post_data);
			// var_dump("POST-DATA: $post_data");	
		}
		if($headers) {
			if($headers['_rev']) {
				$req->addHeader('_rev', (string)$headers['_rev']);
			}

			if($headers['Content-Type']) {
				$req->addHeader('Content-Type', $headers['Content-Type']);
			}
		}
		
		$resp = $req->sendRequest();
		if(PEAR::isError($resp)) {
			return false;
		}
		
		$this->lastStatusCode = $req->getResponseCode();
		
		if(!in_array($this->lastStatusCode, range(200, 299))) {
			return false;
		}
		
		$this->lastRevision = $req->getResponseHeader('x-couch-revid');
		$this->lastDocId = $req->getResponseHeader('x-couch-docid');
		
		
		$json = ($req->getResponseBody());
		$json = preg_replace('/"_rev":([0-9]+)/', '"_rev":"$1"', $json);
		return json_decode($json);
	}
}